<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!-- 其他查询条件 -->
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd"
          v-hasPermi="['merchant:serveCity:add']">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="serveCityList">
      <el-table-column label="推广城市" align="center" prop="addrName" />
      <el-table-column label="地区编码" align="center" prop="addrCode" />
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" :active-value="1" :inactive-value="0"
            @change="handleStatusChange(scope.row, $event)"></el-switch>
          <span :style="{ color: scope.row.status === 0 ? 'red' : 'green' }">{{ scope.row.status === 0 ? '关' : '开' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['merchant:serveCity:edit']">修改</el-button>
          <el-button size="small" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['merchant:serveCity:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="地址信息" prop="addrName">
          <div class="address-selectors">
            <el-select v-model="selectedProvince" clearable placeholder="请选择省份" filterable @change="fetchCities">
              <el-option v-for="(province, index) in filteredProvinces" :key="index" :label="province"
                :value="province"></el-option>
            </el-select>

            <el-select v-model="queryParams.addrName" clearable placeholder="请选择城市" filterable
              :disabled="!selectedProvince">
              <el-option v-for="(city, index) in filteredCities" :key="index" :label="city.city"
                :value="city.cityCode"></el-option>
            </el-select>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listServeCity, getServeCity, delServeCity, addServeCity, updateServeCity, baseInfoExtData } from "@/api/merchant/serveCity";

export default {
  name: "ServeCity",
  data() {
    return {
      loading: true,
      ids: [],
      showSearch: true,
      selectedProvince: '',
      filteredCities: [],
      filteredProvinces: [],
      total: 0,
      serveCityList: [],
      extData: {},
      title: "",
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        infoId: null,
        addrName: null,
        addrCode: null,
        status: null,
      },
      form: {
        id: null,
        infoId: null,
        addrName: null,
        addrCode: null,
        cityCode: null,
      },
      rules: {},
    };
  },
  created() {
    this.getList();
    this.getOptions();
    this.infoId = this.$route.query.infoId;
  },
  methods: {
    fetchCities() {
      this.queryParams.addrName = null; // 清空城市选择
      this.filteredCities = this.extData.addressInfo[this.selectedProvince] || [];
    },

    getOptions() {
      baseInfoExtData().then((response) => {
        this.extData = response.data;
        this.filteredProvinces = Object.keys(this.extData.addressInfo);
      });
    },

    getList() {
      this.loading = true;
      console.log(this.$route.query.infoId);
      this.queryParams.infoId = this.$route.query.infoId;
      listServeCity(this.queryParams).then(response => {
        this.serveCityList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    cancel() {
      this.open = false;
      this.reset();
    },

    reset() {
      this.form = {
        id: null,
        addrName: null,
        addrCode: null,
        cityCode: null,
      };
      this.resetForm("form");
      this.selectedProvince = ''; // 清空省份选择
      this.filteredCities = []; // 清空城市选择
    },

    // 状态修改
    handleStatusChange(row, value) {
      let statusText = (+value) === 0 ? "停用" : "启用";
      updateServeCity({ id: row.id, status: +value }).then(res => {
        this.$modal.msgSuccess(statusText + "成功");
        this.getList(); // 刷新列表以显示新的状态
      }).catch(() => {
        // 如果更新失败，恢复之前的状态
        row.status = row.status == 0 ? 1 : 0;
        this.$modal.msgError(statusText + "失败，请重试");
      });
    },

    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    watch:{
    $route(){
      this.getList()
    }
  },

    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "";
    },

    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getServeCity(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "";
      });
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const selectedCity = this.filteredCities.find(city => city.cityCode === this.queryParams.addrName);
          this.form.addrName = selectedCity ? selectedCity.city : '';
          this.form.addrCode = this.queryParams.addrName;

          if (this.form.id != null) {
            updateServeCity(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.queryParams.addrName = null;
              this.getList();
            });
          } else {
            this.form.infoId = this.queryParams.infoId;
            addServeCity(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.queryParams.addrName = null;
              this.getList();
            });
          }
        }
      });
    },

    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商户服务城市信息编号为"' + ids + '"的数据项？').then(() => {
        return delServeCity(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    handleExport() {
      this.download('merchant/serveCity/export', {
        ...this.queryParams
      }, `serveCity_${new Date().getTime()}.xlsx`);
    },
  }
};
</script>

<style scoped>
.address-selectors {
  display: flex;
  gap: 10px; /* 控制省份和城市选择器之间的间距 */
}

.address-selectors .el-select {
  flex: 1; /* 让选择器平分可用空间 */
}

.dialog-footer {
  text-align: right; /* 按钮右对齐 */
}
</style>
